#!/bin/bash

set -euo pipefail

# Determine the script's directory (even if it's a symbolic link)
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do SOURCE="$(readlink "$SOURCE")"; done
SCRIPTS_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
SRC_DIR="$(cd -P "$(dirname "$SCRIPTS_DIR")" && pwd)"

# List of plugins to build
plugins=(
    "rastervision_pipeline"
    "rastervision_aws_batch"
    "rastervision_aws_s3"
    "rastervision_core"
    "rastervision_pytorch_learner"
    "rastervision_pytorch_backend"
    "rastervision_gdal_vsi"
    "rastervision_aws_sagemaker"
)
# Usage documentation
function usage() {
    echo "Usage: $(basename "$0") [--test]"
    echo ""
    echo "Build Raster Vision plugins and top-level package."
}

# Check for command-line arguments
if [[ ${1:-} == "--help" || ${1:-} == "-h" ]]; then
    usage
    exit
fi

# Function to build a plugin
function build_plugin() {
    pushd "$SRC_DIR/$1" >/dev/null
    echo "Building $1 ... "
    rm -rf build/ dist/ *.egg-info
    python -m build
    echo "Done."
    popd >/dev/null
}

# Build each plugin
for plugin in "${plugins[@]}"; do
    build_plugin "$plugin"
done

# Build the top-level package
pushd "$SRC_DIR" >/dev/null
echo "Building top-level package ... "
rm -rf build/ dist/ *.egg-info
python -m build
echo "Done."
popd >/dev/null
